import { Drawer, Form, Button, Col, Row, Input, DatePicker, Table, InputNumber } from 'antd';
import React, { useContext, useState, useEffect, useRef, Component } from 'react';
import moment from 'moment';
import { EditOutlined } from '@ant-design/icons';
import { Quotationdetail } from '../../../services/auth';
import { getToken } from '../../../utils/auth';

const EditableContext = React.createContext(null);

// editableTable中的行组件
const EditableRow = ({ index, ...props }) => {
	const [ form ] = Form.useForm();
	return (
		<Form form={form} component={false}>
			<EditableContext.Provider value={form}>
				<tr {...props} />
			</EditableContext.Provider>
		</Form>
	);
};

// editableTable中的列组件
const EditableCell = ({ title, editable, children, dataIndex, record, handleSave, ...restProps }) => {
	const [ editing, setEditing ] = useState(false);
	const inputRef = useRef(null);
	const form = useContext(EditableContext);
	useEffect(
		() => {
			if (editing) {
				inputRef.current.focus();
			}
		},
		[ editing ]
	);

	const toggleEdit = () => {
		setEditing(!editing);
		form.setFieldsValue({
			[dataIndex]: record[dataIndex]
		});
	};

	const save = async () => {
		try {
			const values = await form.validateFields();
			toggleEdit();
			handleSave({ ...record, ...values });
		} catch (errInfo) {
			console.log('Save failed:', errInfo);
		}
	};

	let childNode = children;

	if (editable) {
		childNode = editing ? (
			<Form.Item
				style={{
					margin: 0
				}}
				name={dataIndex}
				rules={[
					{
						required: true,
						message: `不能为空`
					}
				]}
				initialValue={100}
			>
				<InputNumber
					min={0}
					max={100}
					formatter={(value) => `${value}%`}
					parser={(value) => value.replace('%', '')}
					ref={inputRef}
					onPressEnter={save}
					onBlur={save}
				/>
			</Form.Item>
		) : (
			<div
				className="editable-cell-value-wrap"
				style={{
					paddingRight: 24
				}}
				onClick={toggleEdit}
			>
				{children}%
			</div>
		);
	}

	return <td {...restProps}>{childNode}</td>;
};

// form中的属性t;
const { RangePicker } = DatePicker;

export default class EditQuotation extends Component {
	constructor(props) {
		super(props);
		const { quotation, handleEditClick } = this.props;
		this.quotation = quotation;
		this.handleEditClick = handleEditClick;
		// 父类的state
		this.state = {
			// 这个是商品数据
			dataSource: [],
			// 这个是可用于生成报价单的询价单列表
			inquiryList: [],
			// 这个用于控制抽屉
			visible: false
		};
		// editableTable的列
		this.columns = [
			{
				title: '产品编号',
				dataIndex: 'goods_id'
			},
			{
				title: '产品名称',
				dataIndex: 'goods_name'
			},
			{
				title: '订货数量',
				dataIndex: 'quantity'
			},
			{
				title: '产品定价',
				dataIndex: 'price'
			},
			{
				title: '折扣（可编辑）',
				dataIndex: 'discount',
				width: '15%',
				editable: true
			},
			{
				title: '产品价格',
				dataIndex: 'current_price'
			}
		];
		this.user = JSON.parse(getToken());
	}
	formRef = React.createRef();
	// 点击提交后触发的事件
	onFinish = (values) => {
		this.handleEditClick({
			id: this.quotation.id,
			goods: this.state.dataSource,
			discount: this.state.dataSource[this.state.dataSource.length - 1].discount,
			total_price: this.state.dataSource[this.state.dataSource.length - 1].current_price,
			company: values.company,
			inquiry_id: values.inq_id,
			operator_id: this.user.id,
			req_deliv_date: values.req_deliv_date.format('YYYY-MM-DD'),
			ship_to_address: values.ship_to_address,
			valid_from: values.valid[0].format('YYYY-MM-DD'),
			valid_to: values.valid[1].format('YYYY-MM-DD')
		});
		this.onClose();
	};
	// 用于editableTable的函数
	handleSave = (row) => {
		const newData = [ ...this.state.dataSource ];
		const index = newData.findIndex((item) => row.key === item.key);
		const item = newData[index];
		newData.splice(index, 1, {
			...item,
			...row,
			current_price: row.discount * row.price / 100
		});
		let sum = 0;
		for (let j = 0, len = newData.length; j < len; j++) {
			if (newData[j].quantity && newData[j].current_price) {
				sum += newData[j].quantity * newData[j].current_price;
			}
		}
		if (row.key !== newData.length - 1) {
			newData.splice(newData.length - 1, 1, {
				key: newData.length - 1,
				goods_id: '总计',
				price: sum,
				current_price: sum
			});
		}
		this.setState({
			dataSource: newData
		});
	};
	// 用于抽屉的函数
	showDrawer = () => {
		this.setState({
			visible: true
		});
	};

	onClose = () => {
		this.setState({
			visible: false
		});
	};

	componentDidMount() {
		Quotationdetail(this.quotation.id).then(
			(response) => {
				//拿到我们想要渲染的数据(res)
				this.setState({
					dataSource: [
						...response.data.goods,
						{
							key: response.data.goods.length,
							goods_id: '总计',
							discount: response.data.discount,
							current_price: response.data.total_price
						}
					]
				});
			},
			(error) => {
				console.log('失败了', error);
			}
		);
	}

	render() {
		const { quotation } = this.props;
		// 拿到editableTable的属性

		const { dataSource } = this.state;
		const components = {
			body: {
				row: EditableRow,
				cell: EditableCell
			}
		};
		const columns = this.columns.map((col) => {
			if (!col.editable) {
				return col;
			}

			return {
				...col,
				onCell: (record) => ({
					record,
					editable: col.editable,
					dataIndex: col.dataIndex,
					title: col.title,
					handleSave: this.handleSave
				})
			};
		});
		return (
			<div>
				<Button type="link" onClick={this.showDrawer} size="small" icon={<EditOutlined />} style={{ fontWeight:"bold"}}>
					编辑
				</Button>
				<Drawer
					title="修改报价单信息"
					width={1000}
					onClose={this.onClose}
					visible={this.state.visible}
					bodyStyle={{ paddingBottom: 80 }}
				>
					<Form layout="vertical" hideRequiredMark onFinish={this.onFinish} ref={this.formRef}>
						<Row gutter={24}>
							<Col span={6}>
								<Form.Item name="id" label="报价单编号" initialValue={quotation.id}>
									<Input disabled />
								</Form.Item>
							</Col>
							<Col span={6}>
								<Form.Item name="inq_id" label="询价单编号" initialValue={quotation.inquiry_id}>
									<Input disabled />
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item
									name="company"
									label="公司"
									initialValue={quotation.company_id + ' ' + quotation.company_name}
								>
									<Input disabled />
								</Form.Item>
							</Col>
						</Row>
						<Row gutter={24}>
							<Col span={8}>
								<Form.Item
									name="valid"
									label="生效期限"
									initialValue={[
										moment(quotation.valid_from, 'YYYY-MM-DD'),
										moment(quotation.valid_to, 'YYYY-MM-DD')
									]}
								>
									<RangePicker />
								</Form.Item>
							</Col>
							<Col span={4}>
								<Form.Item
									name="req_deliv_date"
									label="预计送达日期"
									initialValue={moment(quotation.req_deliv_date, 'YYYY-MM-DD')}
								>
									<DatePicker disabled />
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item name="ship_to_address" label="送货地点" initialValue={quotation.ship_to_address}>
									<Input disabled />
								</Form.Item>
							</Col>
						</Row>
						<Row gutter={24} />
						{/* editableTable */}
						<Table
							components={components}
							rowClassName={() => 'editable-row'}
							bordered
							dataSource={dataSource}
							columns={columns}
							pagination={false}
						/>

						<Form.Item>
							<div
								style={{
									textAlign: 'right'
								}}
							>
								<Button type="primary" htmlType="submit">
									保存
								</Button>
							</div>
						</Form.Item>
					</Form>
				</Drawer>
			</div>
		);
	}
}
